<!-- CommentWall.vue -->
<template>
  <div class="comment-wall-container">
    <!-- 侧边栏 -->
    <aside class="sidebar">
      <div class="sidebar-inner">
        <!-- Logo -->
        <div class="logo-container">
          <div class="logo-badge">
            <el-icon class="logo-icon"><ChatLineSquare /></el-icon>
          </div>
          <h1 class="logo-text">校园评论墙</h1>
        </div>

        <!-- 分类导航 -->
        <nav class="category-nav">
          <div class="category-header">
            <span>热门话题</span>
          </div>
          <el-menu
            :default-active="currentCategory"
            class="category-menu"
            @select="handleCategoryChange"
          >
            <el-menu-item
              v-for="tag in tagList"
              :key="tag.tagId"
              :index="tag.tagId.toString()"
              class="category-item"
            >
              <span>{{ tag.tagName }}</span>
              <el-badge :value="getTagCount(tag.tagId)" class="tag-badge" type="info" v-if="getTagCount(tag.tagId) > 0" />
            </el-menu-item>
          </el-menu>
        </nav>

        <!-- 底部用户信息 -->
        <div class="user-info">
          <div class="user-info-inner">
            <el-avatar
              :size="50"
              :src="getUserAvatar(userInfo)"
              class="user-avatar-img"
            />
            <div class="user-details">
              <div class="username">{{ userInfo.username || "未登录" }}</div>
              <el-button 
                size="small" 
                @click="$router.push('/share/my-shares')"
                class="my-shares-btn"
                type="primary"
                plain
              >
                <el-icon class="mr-1"><Document /></el-icon>
                我的分享
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </aside>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 顶部工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索评论..."
            class="search-input"
            :prefix-icon="Search"
            @input="handleSearch"
            clearable
          />
        </div>
        <div class="toolbar-right">
          <div class="sort-options">
            <el-radio-group v-model="sortType" size="large" class="sort-group" @change="handleSortChange">
              <el-radio-button label="newest">最新</el-radio-button>
              <el-radio-button label="hottest">最热</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </div>

      <!-- 评论发布表单 -->
      <div class="publish-form">
        <el-form @submit.prevent="handleSubmit">
          <div class="form-header">
            <span class="form-title">分享你的想法</span>
          </div>
          <el-input
            v-model="newComment.content"
            type="textarea"
            :rows="3"
            placeholder="在这里输入你想分享的内容..."
            resize="none"
            maxlength="500"
            show-word-limit
            class="publish-textarea"
          />
          <div class="form-footer">
            <div class="form-controls">
              <el-select
                v-model="newComment.tags"
                multiple
                placeholder="选择标签 (最多3个)"
                :multiple-limit="3"
                class="tag-select"
              >
                <el-option
                  v-for="tag in tagList"
                  :key="tag.tagId"
                  :label="tag.tagName"
                  :value="tag.tagId"
                />
              </el-select>
            </div>
            <el-button
              type="primary"
              :disabled="!newComment.content || submitting"
              :loading="submitting"
              @click="handleSubmit"
              class="publish-btn"
              round
            >
              <el-icon class="mr-1"><Plus /></el-icon>
              发布评论
            </el-button>
          </div>
        </el-form>
      </div>

      <!-- 评论列表 -->
      <div v-loading="loading" class="comment-list">
        <el-empty v-if="shareList.length === 0" description="暂无评论" />
        
        <transition-group name="comment-fade" tag="div" class="comment-list-container">
          <el-card
            v-for="share in shareList"
            :key="share.shareId"
            class="comment-card"
            @click="navigateToDetail(share.shareId)"
            shadow="hover"
          >
            <div class="comment-content">
              <div class="content-header">
                <div class="user-meta">
                  <el-avatar :size="46" :src="getUserAvatar(share)" class="avatar" />
                  <div class="user-info-meta">
                    <span class="author">{{ share.createBy }}</span>
                    <span class="time">
                      {{ formatTime(share.createTime) }}
                    </span>
                  </div>
                </div>
                <div class="tag-container">
                  <el-tag
                    v-for="(tagId, index) in share.tagsId"
                    :key="tagId"
                    size="small"
                    effect="light"
                    class="tag"
                    :style="{marginLeft: index > 0 ? '4px' : '0'}"
                  >
                    {{ getTagName(tagId) }}
                  </el-tag>
                </div>
              </div>
              <div class="content-body">
                <p class="text">{{ share.content }}</p>
              </div>
              <div class="content-footer">
                <div class="stats">
                  <span class="stat-item"><el-icon><ChatDotSquare /></el-icon>{{ share.commentCount || 0 }}</span>
                </div>
                <div class="actions">
                  <el-button
                    type="primary"
                    size="small"
                    text
                    @click.stop="navigateToDetail(share.shareId)"
                    class="view-detail-btn"
                  >
                    查看详情
                  </el-button>
                  <el-button
                    v-if="canDelete(share)"
                    type="danger"
                    size="small"
                    text
                    @click.stop="handleDelete(share.shareId)"
                    class="delete-btn"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </transition-group>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-if="total > 0"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ChatLineSquare, Search, ChatDotSquare, Document, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import { 
  getShareList, 
  getShareByTag, 
  getAllTags,
  addShare,
  deleteShare
} from '@/api/share'
import { useUserStore } from '@/store/user'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const router = useRouter()
const userStore = useUserStore()

// 状态数据
const loading = ref(false)
const submitting = ref(false)
const searchKeyword = ref('')
const sortType = ref('newest')
const currentCategory = ref('')
const shareList = ref([])
const tagList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const defaultAvatar = '/src/assets/user-avatar.svg'

// 新评论表单
const newComment = ref({
  content: '',
  tags: []
})

// 用户信息
const userInfo = computed(() => {
  return {
    userId: userStore.userId,
    username: userStore.userInfo?.nickname || userStore.userInfo?.username || '未登录',
    avatar: userStore.userInfo?.avatar || defaultAvatar
  }
})

// 获取用户头像
const getUserAvatar = (share) => {
  // 优先使用分享中的用户头像
  if (share.avatar) {
    return share.avatar
  }
  
  // 如果是当前用户，使用当前用户头像
  if (userStore.isLoggedIn && share.userId === userStore.userInfo?.userId) {
    return userStore.userInfo?.avatar || defaultAvatar
  }
  
  // 默认返回通用头像
  return defaultAvatar
}

// 获取标签名称
const getTagName = (tagId) => {
  const tag = tagList.value.find(t => t.tagId === tagId)
  return tag ? tag.tagName : tagId
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).fromNow()
}

// 是否可以删除
const canDelete = (share) => {
  return share.userId === userStore.userId || userStore.isAdmin
}

// 获取分享列表
const fetchShareList = async () => {
  loading.value = true
  try {
    const res = await getShareList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    })
    
    if (res.code === 0 || res.code === 200) {
      shareList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 获取标签列表
const fetchTags = async () => {
  try {
    const res = await getAllTags()
    if (res.code === 0 || res.code === 200) {
      tagList.value = res.data || []
    } else {
      console.error('获取标签列表失败:', res.message)
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 根据标签筛选
const filterByTagId = async (tagId) => {
  if (!tagId) {
    fetchShareList()
    return
  }
  
  loading.value = true
  try {
    const res = await getShareByTag(tagId)
    if (res.code === 0 || res.code === 200) {
      shareList.value = res.data || []
      total.value = shareList.value.length
    } else {
      ElMessage.error(res.message || '获取标签分享失败')
    }
  } catch (error) {
    console.error('获取标签分享失败:', error)
    ElMessage.error('获取标签分享失败')
  } finally {
    loading.value = false
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    return
  }
  
  if (!newComment.value.content.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  submitting.value = true
  try {
    const data = {
      userId: userStore.userId,
      createBy: userStore.username,
      content: newComment.value.content,
      tags: newComment.value.tags
    }
    
    const res = await addShare(data)
    
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('发布成功')
      newComment.value = {
        content: '',
        tags: []
      }
      await fetchShareList()
    } else {
      ElMessage.error(res.message || '发布失败')
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败')
  } finally {
    submitting.value = false
  }
}

// 处理分类切换
const handleCategoryChange = (tagId) => {
  currentCategory.value = tagId
  currentPage.value = 1
  filterByTagId(tagId)
}

// 处理排序方式变化
const handleSortChange = () => {
  currentPage.value = 1
  fetchShareList()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchShareList()
}

// 导航到详情页
const navigateToDetail = (shareId) => {
  router.push(`/share/${shareId}`)
}

// 删除评论
const handleDelete = async (shareId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条分享吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteShare(shareId)
    
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('删除成功')
      await fetchShareList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchShareList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchShareList()
}

// Add this function to compute tag counts
const getTagCount = (tagId) => {
  return shareList.value.filter(share => 
    share.tagsId && share.tagsId.includes(tagId)
  ).length;
}

onMounted(() => {
  fetchTags()
  fetchShareList()
})

// 监听分类变化
watch(currentCategory, (tagId) => {
  if (tagId) {
    filterByTagId(tagId)
  } else {
    fetchShareList()
  }
})
</script>

<style scoped>
.comment-wall-container {
  display: flex;
  height: calc(100vh - 64px);
  background-color: #f5f7fa;
  overflow: hidden;
}

/* Sidebar Styles */
.sidebar {
  width: 250px;
  background-color: #fff;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 10;
  transition: width 0.3s;
}

.sidebar-inner {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 1.5rem 1rem;
}

.logo-container {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
}

.logo-badge {
  background-color: #4d7cfe;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 0.5rem;
  box-shadow: 0 4px 8px rgba(77, 124, 254, 0.25);
}

.logo-icon {
  font-size: 24px;
  color: #fff;
}

.logo-text {
  font-size: 1.5rem;
  font-weight: 600;
  background: linear-gradient(45deg, #4d7cfe, #6e8efb);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.category-nav {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 1.5rem;
}

.category-header {
  margin: 0 0.5rem 1rem;
  font-weight: 600;
  color: #606266;
  font-size: 1rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.category-menu {
  border-right: none !important;
}

.category-item {
  display: flex;
  justify-content: space-between !important;
  align-items: center;
  margin: 0.25rem 0;
  border-radius: 6px;
  padding: 0.5rem 1rem;
  height: auto !important;
  line-height: normal !important;
}

.tag-badge {
  margin-left: 0.5rem;
}

.user-info {
  padding-top: 1rem;
  border-top: 1px solid #eaeaea;
}

.user-info-inner {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.user-avatar-img {
  border: 2px solid white;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.username {
  font-weight: 600;
  color: #2c3e50;
}

.my-shares-btn {
  width: 100%;
}

/* Main Content Styles */
.main-content {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  background-color: #f5f7fa;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1.5rem;
  gap: 1rem;
  align-items: center;
}

.toolbar-left {
  flex: 1;
}

.search-input {
  max-width: 300px;
}

.toolbar-right {
  display: flex;
  gap: 1rem;
}

.sort-options {
  display: flex;
  align-items: center;
}

.sort-group :deep(.el-radio-button__inner) {
  border-radius: 4px;
  padding: 8px 16px;
  color: #606266;
  font-weight: 500;
}

.sort-group :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background-color: #4d7cfe;
  border-color: #4d7cfe;
  color: white;
  box-shadow: -1px 0 0 0 #4d7cfe;
}

.publish-form {
  background-color: white;
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.publish-form:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.form-header {
  margin-bottom: 1rem;
}

.form-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2c3e50;
}

.publish-textarea {
  width: 100%;
  margin-bottom: 1rem;
  border-radius: 8px;
}

.form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

.form-controls {
  flex: 1;
}

.tag-select {
  width: 100%;
}

.publish-btn {
  min-width: 120px;
}

.comment-list {
  min-height: 200px;
  margin-bottom: 2rem;
}

.comment-list-container {
  display: flex;
  flex-direction: column;
  gap: 0.85rem;
}

.comment-card {
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  background-color: white;
  position: relative;
  margin-bottom: 0;
}

.comment-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1) !important;
}

.comment-content {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.content-body {
  padding: 0 0.5rem;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
}

.user-meta {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.avatar {
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.user-info-meta {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.author {
  font-weight: 600;
  color: #2c3e50;
}

.time {
  font-size: 0.8rem;
  color: #909399;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag {
  font-size: 0.8rem;
}

.text {
  color: #303133;
  line-height: 1.6;
  margin: 0.25rem 0;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  font-size: 0.95rem;
}

.content-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.5rem;
  padding-top: 0.5rem;
  border-top: 1px solid #f0f2f5;
}

.stats {
  display: flex;
  gap: 1rem;
  color: #909399;
  font-size: 0.9rem;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.actions {
  display: flex;
  gap: 0.5rem;
}

.view-detail-btn {
  font-size: 0.85rem;
}

.delete-btn {
  font-size: 0.85rem;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 2rem;
  padding: 1rem 0;
}

/* Animation effects */
.comment-fade-enter-active,
.comment-fade-leave-active {
  transition: all 0.5s ease;
}

.comment-fade-enter-from,
.comment-fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .comment-wall-container {
    flex-direction: column;
    height: auto;
  }

  .sidebar {
    width: 100%;
    height: auto;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }

  .sidebar-inner {
    flex-direction: row;
    padding: 1rem;
    align-items: center;
    justify-content: space-between;
  }

  .logo-container {
    margin-bottom: 0;
  }

  .category-nav {
    display: none;
  }

  .user-info {
    border-top: none;
    padding-top: 0;
  }

  .comment-grid {
    grid-template-columns: 1fr;
  }
}
</style> 